﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RealEstate.Models;
using Telerik.Web.UI;

namespace RealEstate.Views.Admin
{
    public partial class ManageCity : System.Web.UI.Page
    {
        private int? _stateId;
        public int StateId
        {
            get
            {

                var stateId = Request.QueryString["sid"];

                if (!string.IsNullOrEmpty(stateId))
                {
                    try
                    {
                        _stateId = Convert.ToInt32(stateId);
                    }
                    catch (Exception)
                    {
                        _stateId = null;
                    }
                }


                return _stateId ?? 0;
            }
        }

        private CityEntities _dbContext;
        public CityEntities DbContext
        {
            get { return _dbContext ?? (_dbContext = new CityEntities()); }
        }

        protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = DbContext.GetByStateId(StateId);
        }

        protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            var item = e.Item as GridEditableItem;
            if (item != null)
            {
                var id = item.GetDataKeyValue("Id").ToString();
                var clientType = DbContext.GetById(Convert.ToInt32(id));
                item.UpdateValues(clientType);
                DbContext.Update(clientType);
            }
        }

        protected void RadGrid1_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            var id = ((GridDataItem)e.Item).GetDataKeyValue("Id").ToString();
            DbContext.Delete(Convert.ToInt32(id));
        }

        protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
        {
            var item = e.Item as GridEditableItem;
            var values = new Hashtable();
            var city = new City();
            if (item != null)
            {
                item.ExtractValues(values);
                item.UpdateValues(city);
                if (!string.IsNullOrEmpty(city.City1))
                {
                    city.StateId = StateId;
                    DbContext.Add(city);
                }
                else
                    return;
            }
        }
    }
}